﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_Material_TempBusiness : BaseBusiness<PB_Material_Temp>, IPB_Material_TempBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_Material_TempBusiness(IDbAccessor db,
            IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_Material_Temp>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_Material_Temp>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Material_Temp, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_Material_Temp> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_Material_Temp data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_Material_Temp data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public  async Task<PageResult<PB_Material_TempDTO>> QueryDataListAsync(PageInput<PBMateria_TemplConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_Material_Temp, PB_MaterialType, Base_UnitGroup, PB_ProcecureSub, PB_Material_TempDTO>> select = (a, b, c, d) => new PB_Material_TempDTO
            {
                MaterialTypeName = b.Name,
                UnitGroupName = c.Name,
                ProcecureName = d.Name,
                Typeid = b.Id,
                MaterialTypeCode = b.Code
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_MaterialType>() on a.MaterialTypeId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_UnitGroup>() on a.UnitGroupId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_ProcecureSub>() on a.ProcecureId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            var where = LinqHelper.True<PB_Material_TempDTO>();
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Material_TempDTO, bool>(
                    ParsingConfig.Default, false, $@"Name.Contains(@0) or Code.Contains(@0) or SimpleName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.MaterialTypeId.IsNullOrEmpty())
            {
                //获取当前选中的物料类型实体
                PB_MaterialType mtype = await Db.GetIQueryable<PB_MaterialType>().FirstOrDefaultAsync(x => x.Id.Equals(search.MaterialTypeId));
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Material_TempDTO, bool>(
                    ParsingConfig.Default, false, $@"MaterialTypeCode.Contains(@0)", mtype.Code);
                where = where.And(newWhere);
            }
      
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task AddDataExlAsync(List<PB_Material_Temp> list, RedisOptions _redisOptions, MongoDBOptions _mongodbOptions)
        {
            //await InsertAsync(list);
            string QrCode = string.Empty;
            string num = string.Empty;
            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            #region  查询登录人最上级的组织id
            string deptId = string.Empty;
            var deptdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
            if (deptdata.Type == 1)
            {
                deptId = deptdata.Id;
            }
            else
            {
                if (deptId.IsNullOrEmpty())
                {
                    string parentId = deptdata.ParentId;
                    do
                    {
                        var data = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == parentId).FirstOrDefaultAsync();
                        if (data.Type != 1)
                        {
                            parentId = data.ParentId;
                        }
                        else
                        {
                            deptId = data.Id;
                        }
                    } while (deptId == "");
                }
            }
            #endregion
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            foreach (var item in list)
            {
                QrCode = "04," + item.MaterialTypeId + "," + _operator.Property.DepartmentId + "," + item.Id + "," + DateTime.Now.ToString("yyMMdd");
                //if (item.IsNumber == true)
                //{
                //    #region  序列号取值
                //    if (RedisSetHelper.Exists("MaterialSerialNumber"))
                //    {
                //        if (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) == 0 && redis.GetString("MaterialSerialNumber") != "99999")
                //        {
                //            redis.SetString("MaterialSerialNumber", (Convert.ToInt32(redis.GetString("MaterialSerialNumber")) + 1).ToString());
                //            num = redis.GetString("MaterialSerialNumber").PadLeft(5, '0');
                //        }
                //        else if (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) == 0 && redis.GetString("MaterialSerialNumber") == "99999")
                //        {
                //            redis.SetString("MaterialSerialNumber", "1");
                //            redis.SetString("MaterialSerialChoice", (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) + 1).ToString());
                //            string KeyChoice = redis.GetString("MaterialSerialChoice");
                //            num = redis.GetHashIn("MaterialSerialAZ", KeyChoice) + redis.GetString("MaterialSerialNumber").PadLeft(5, '0');
                //        }
                //        else if (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) != 0 && redis.GetString("MaterialSerialNumber") != "99999")
                //        {
                //            string KeyChoice = redis.GetString("MaterialSerialChoice");
                //            num = redis.GetHashIn("MaterialSerialAZ", KeyChoice) + redis.GetString("MaterialSerialNumber").PadLeft(5, '0');
                //        }
                //        else if (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) != 0 && redis.GetString("MaterialSerialNumber") == "99999")
                //        {
                //            redis.SetString("MaterialSerialNumber", "1");
                //            redis.SetString("MaterialSerialChoice", (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) + 1).ToString());
                //            string KeyChoice = redis.GetString("MaterialSerialChoice");
                //            num = redis.GetHashIn("MaterialSerialAZ", KeyChoice) + redis.GetString("MaterialSerialNumber").PadLeft(5, '0');
                //        }
                //    }
                //    else
                //    {
                //        redis.SetString("MaterialSerialNumber", "0");
                //        redis.SetString("MaterialSerialChoice", (Convert.ToInt32(redis.GetString("MaterialSerialChoice")) + 1).ToString());
                //        num = redis.GetString("MaterialSerialNumber").PadLeft(5, '0');
                //    }
                //    QrCode += "," + num;
                //    #endregion
                //}
                item.QrCode = QrCode;
                item.DeptId = deptId;
            }
        
            //mongo.Add<ErrLog>(ErrLogCollection, err);
            try
            {
                Db.BulkInsert<PB_Material_Temp>(list);

                //await InsertAsync(list); 
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        #endregion

        #region 私有成员

        #endregion
    }
}